<?php

namespace app\common\model;

use app\admin\model\Config;
use EasyWeChat\Factory;
use think\Exception;
use think\Model;
use function form\e;

/**
 * 邮箱验证码
 */
class UserModel extends Model
{
    protected $autoWriteTimestamp = true;
    protected $name = 'user';


    /*
 * 微信授权登录
 */
    public function wxLogin($params)
    {
        try {
            if (empty($params['code'])) {
                throw new Exception('缺少参数');
            }
            // 获取授权appid
            $app = Factory::miniProgram(config('wechat.xcx'));

            $data = $app->auth->session($params['code']);

            if (!$data) {
                throw new Exception('获取sessionKey和openId时异常');
            }

            if (!empty($data['errcode']) && $data['errcode'] != 0) {
                throw new Exception($data['errmsg']);
            }

            $userInfo = self::where(['openid' => $data['openid']])->find();


            $time = time();
            if (!$userInfo) {
                //用户不存在，创建用户
                $insert['nickname'] = "微信用户";
                $insert['openid'] = $data['openid'];
                $insert['create_time'] = $time;
                $insert['update_time'] = $time;
                $userId = \think\Db::name('user')->insertGetId($insert);
            } else {
                if($userInfo['status'] == 0){
                    throw new Exception('您的账号已被封禁');
                }

                $userId = $userInfo['id'];
            }
            //查询用户信息
            $wxUserMes = \think\Db::name('user')
                ->field('id as user_id,nickname,avatar,status')
                ->where('id', $userId)
                ->find();

            $wxUserMes['user_token'] = (new Token())->product_token($wxUserMes['user_id'], 1);

            return ['code' => 200, 'msg' => '获取信息成功', 'data' => $wxUserMes];

        } catch (\Exception $e) {
            return ['code' => 201, 'msg' => $e->getMessage()];

        }
    }


    public function accLogin($params)
    {
        try {
            if (empty($params['phone']) || empty($params['password'])) {
                throw new Exception('缺少参数');
            }

            $phone = trim($params['phone']);
            $password = trim($params['password']);
            $admin = UserModel::get(['phone' => $phone]);
            if (!$admin) {
                throw new Exception('用户名不正确');
            }
            if ($admin['status'] !== 1) {
                throw new Exception('管理员已经被禁止登录');
            }
            if ($admin->password != encrypt_password($password, $admin->encrypt)) {
                throw new Exception('密码不正确');
            }

            $wxUserMes['user_token'] = (new Token())->product_token($admin['id'], 1);
            $wxUserMes['user_id'] = $admin->id;

            return ['code' => 200, 'msg' => '获取信息成功', 'data' => $wxUserMes];

        } catch (\Exception $e) {
            return ['code' => 201, 'msg' => $e->getMessage()];

        }
    }


    /*
     * 保存个人信息
     */
    public function saveInfo($params)
    {
        $user = self::where(['id' => $params['user_id']])->find();
        if (!$user) {
            return ['code' => 201, 'msg' => '用户不存在'];
        }
        $user->nickname = $params['nickname'];
        $user->avatar = $params['avatarUrl'];

        if ($user->save()) {
            return ['code' => 200, 'msg' => '保存成功', 'data' => $user->toArray()];
        }
        return ['code' => 201, 'msg' => '系统错误，请重新尝试！'];

    }


    /*
    * 保存个人信息
    */
    public function saveCard($params)
    {
        $user = self::where(['id' => $params['user_id']])->find();
        if (!$user) {
            return ['code' => 201, 'msg' => '用户不存在'];
        }


        $userCard = (new CardModel())->where(['uid' => $user['id']])->find();
        if(!$userCard){
            $userCard = (new CardModel());
        }
        try {
            $data = $params['params'];
            $userCard->username = $data['username'];
            $userCard->uid = $params['user_id'];
            $userCard->card_code = $data['card_code'];
            $userCard->phone = $data['phone'];
            $userCard->id_number = $data['id_number'];
            $userCard->card1 = $data['card1_img'];
            $userCard->card2 = $data['card2_img'];

            if ($userCard->save()) {
                return ['code' => 200, 'msg' => '保存成功'];
            }
            return ['code' => 201, 'msg' => '系统错误，请重新尝试！'];
        }catch(Exception $e){
            print_r($e->getMessage());die;
        }


    }


    public function saveAlipay($params)
    {
        $user = self::where(['id' => $params['user_id']])->find();
        if (!$user) {
            return ['code' => 201, 'msg' => '用户不存在'];
        }


        $userCard = (new ZfbModel())->where(['uid' => $user['id']])->find();
        if(!$userCard){
            $userCard = (new ZfbModel());
        }
        try {
            $data = $params['params'];
            $userCard->username = $data['username'];
            $userCard->uid = $params['user_id'];
            $userCard->card_code = $data['card_code'];
            $userCard->phone = $data['phone'];
            $userCard->id_number = $data['id_number'];
            $userCard->card1 = $data['card1_img'];
            $userCard->card2 = $data['card2_img'];

            if ($userCard->save()) {
                return ['code' => 200, 'msg' => '保存成功'];
            }
        }catch(Exception $e){
            return ['code' => 201, 'msg' => $e->getMessage()];

        }


    }


    public function getUserInfo($params)
    {
        $user = self::where(['id' => $params['user_id']])->field('id,nickname,avatar,card1,card2')->find();
        if (!$user) {
            return ['code' => 201, 'msg' => '用户不存在'];
        }

        if($user['avatar']){
            $user['avatar'] = config('app.api_url') . $user['avatar'];
        }

        return ['code' => 200, 'msg' => '获取成功', 'data' => $user];
    }


    public function getPhone()
    {
        $config = (new Config())->where(['id' => [15, 16,17]])->column('value', 'name');
        return ['code' => 200, 'msg' => '获取成功', 'data' => $config];
    }


    public function problem($params)
    {
        $model = (new ProblemModel());
        $model->uid = $params['user_id'];
        $model->content = $params['content'];

        if ($model->save()) {
            return ['code' => 200, 'msg' => '提交成功'];
        }

        return ['code' => 201, 'msg' => '提交失败'];
    }


    public function loginOut($parma)
    {
        $token = \think\Db::name('user_token')->where(['user_id' => $parma['user_id']])->delete();
        if ($token) {
            return ['code' => 200, 'msg' => '退出成功', 'data' => []];
        }
        return ['code' => 201, 'msg' => '退出失败'];
    }


    public function getLists($params)
    {
        $where[] = ['day','>=',$params['startTime']];
        $where[] = ['day','<=',$params['endTime']];
        $where[] = ['uid','=',$params['user_id']];
        $where[] = ['zid','>',0];

        $list = InComemModel::where($where)
            ->order("day {$params['sort']}")
            ->paginate($params['limit'], false, ['page' => $params['page']]);

        $money =number_format(InComemModel::where($where)->sum('money'), 2);
        return ['code' => 200, 'msg' => '获取信息成功', 'data' => ['list' => $list, 'money' => $money]];
    }


    public function getCard($params){
         $userCard = (new CardModel())->where(['uid' => $params['user_id']])->find();
        return ['code' => 200, 'msg' => '退出成功', 'data' => $userCard];
    }

    public function getAlipay($params){
        $userCard = (new ZfbModel())->where(['uid' => $params['user_id']])->find();

        return ['code' => 200, 'msg' => '退出成功', 'data' => $userCard];
    }

    public function deleteCard($params){
        $userCard = (new CardModel())->where(['uid' =>$params['user_id']])->find();
        if(!$userCard){
            return ['code' => 201, 'msg' => '数据不存在', 'data' => []];
        }
        if($userCard->delete()){
            return ['code' => 200, 'msg' => '删除成功', 'data' => $userCard];
        }

        return ['code' => 201, 'msg' => '删除失败', 'data' => $userCard];
    }

    public function deleteAlipay($params){
        $userCard = (new ZfbModel())->where(['uid' =>$params['user_id']])->find();
        if(!$userCard){
            return ['code' => 201, 'msg' => '数据不存在', 'data' => []];
        }
        if($userCard->delete()){
            return ['code' => 200, 'msg' => '删除成功', 'data' => $userCard];
        }

        return ['code' => 201, 'msg' => '删除失败', 'data' => $userCard];
    }
}
